package jwt

import (
	"encoding/json"
	"errors"
	"github.com/golang-jwt/jwt/v4"
	"time"
)

type Jwt struct {
	SigningKey  string
	ExpiresTime int64
}

var (
	TokenExpired     = errors.New("Token is expired")
	TokenNotValidYet = errors.New("Token not active yet")
	TokenMalformed   = errors.New("That's not even a token")
	TokenInvalid     = errors.New("Couldn't handle this token:")
)

func NewJwt(config string) *Jwt {
	var jwt Jwt
	json.Unmarshal([]byte(config), &jwt)
	return &jwt
}

// 创建token
func (p Jwt) CreateToken(data interface{}) (string, error) {
	baseClaims := jwt.MapClaims{
		"exp": time.Now().Unix() + p.ExpiresTime,
		"iat": time.Now().Unix(),
		"iss": "client.apivueamdin",
		"aud": "server.apivueadmin",
	}
	tmp, _ := json.Marshal(data)
	var otherclaims map[string]interface{}
	json.Unmarshal(tmp, &otherclaims)
	for key, val := range otherclaims {
		baseClaims[key] = val
	}
	claims := jwt.NewWithClaims(jwt.SigningMethodHS256, baseClaims)
	signingString, err := claims.SignedString([]byte(p.SigningKey))
	if err != nil {
		return "", err
	}
	return signingString, nil
}

// 解析token
func (p Jwt) ParseToken(tokenstr string) (jwt.Claims, error) {
	token, err := jwt.ParseWithClaims(tokenstr, jwt.MapClaims{}, func(token *jwt.Token) (i interface{}, e error) {
		return []byte(p.SigningKey), nil
	})
	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				return nil, TokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, TokenNotValidYet
			} else {
				return nil, TokenInvalid
			}
		}
	}
	if token != nil && token.Valid {
		return token.Claims, nil
	} else {
		return nil, TokenInvalid
	}
}
